var crypto = require('crypto');
var DOMParser = require('xmldom').DOMParser;
// 加载underscore
var _ = require ( 'underscore' ). _ ;
var Class = require('class-extender');

var fs = require('fs');//文件模块
var buffer = require('buffer');//文件模块
var path = require('path');//路径模块

var AbsPathPD = {
  papp:'/www/这里是路径/',
  pwww:'/www/这里是路径/',
  dapp:'C:/这里是路径/',
  dwww:'D:/Projects/这里是路径/'
};
exports.FixedNumber = 5;

exports.CopyFile = function(src, dst) {
  fs.writeFileSync(dst, fs.readFileSync(src));
};
exports.MoveFile = function(src, dst) {
  fs.writeFileSync(dst, fs.readFileSync(src));
  fs.unlinkSync(src);
};
exports.GetAbsPath = function(ehostname,es){
  var ep = es || '';
  var iapppath, iwwwpath;
  if(ehostname=='miaoxiaoer.com' || ehostname=='www.miaoxiaoer.com'){
    iapppath = AbsPathPD.papp;
    iwwwpath = AbsPathPD.pwww;
  }else{
    iapppath = AbsPathPD.dapp;
    iwwwpath = AbsPathPD.dwww;
  }
  return {"www":iwwwpath + ep, "app":iapppath + ep, "xiangdui":"./" + ep};
};

exports.RandomString = function(eletters, elen){
  elen = elen || 32;
  var imaxPos = eletters.length;
  var icode = '';
  for (var i = 0; i < elen; i++) {
    icode += eletters.charAt(Math.floor(Math.random() * imaxPos));
  }
  return icode;
}


exports.Utf82Base64 = function(estring){
  var b = new Buffer(estring);
  var s = b.toString('base64');
  return s;
};
exports.Base642Utf8 = function(estring){
  var b = new Buffer(estring, 'base64')
  var s = b.toString();
  return s;
};

exports.MiaoMD5 = function(estring){
  var md5 = crypto.createHash('md5');
  md5.update(estring);
  var d = md5.digest('hex');  //MD5值是5f4dcc3b5aa765d61d8327deb882cf99
  return d;
};

exports.MiaoSHA1 = function(estring){
  var crypto = require('crypto');
  var shasum = crypto.createHash('sha1');
  shasum.update(estring);
  var d = shasum.digest('hex');
  return d;
};

exports.MiaoEncode = function(estring,ekey){
  ekey = ekey || 'Tuine=6#-32198780Sog';
  var encrypted = '';
  var cip = crypto.createCipher('aes-256-ecb', ekey);
  encrypted += cip.update(estring, 'utf-8', 'hex');
  encrypted += cip.final('hex');
  return encrypted;
};

exports.MiaoDecode = function (estring,ekey){
  ekey = ekey || 'Tuine=6#-32198780Sog';
  var decrypted = '';
  var decipher = crypto.createDecipher('aes-256-ecb', ekey);
  decrypted += decipher.update(estring, 'hex', 'utf-8');
  decrypted += decipher.final('utf-8');
  return decrypted ;
};

// 判断是否为json对象
exports.IsJson = function(e) {
  var isjson = typeof (e) == 'object' && Object.prototype.toString.call(e).toLowerCase() == '[object object]' && !e.length;
  return isjson;
};

exports.getNowFormatDate = function() {
    var date = new Date();
    var seperator1 = '-';
    var month = date.getMonth() + 1;
    var monthstr = '' + month;
    var strDate = date.getDate();
    var strDatestr = '' + strDate;
    if (month >= 1 && month <= 9) {
      monthstr = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDatestr = '0' + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + monthstr + seperator1 + strDatestr
            + '';
    return currentdate;
}
exports.getNowFormatDateTime = function() {
    var date = new Date();
    var seperator1 = '-';
    var seperator2 = ':';
    var month = date.getMonth() + 1;
    var monthstr = '' + month;
    var strDate = date.getDate();
    var strDatestr = '' + strDate;
    if (month >= 1 && month <= 9) {
      monthstr = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDatestr = '0' + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + monthstr + seperator1 + strDatestr
            + '' + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
};
exports.HtmlEncode = function(estr){
  estr = estr.replace(/&/g, "&amp;");
  estr = estr.replace(/</g, '&lt;');
  estr = estr.replace(/>/g, '&gt;');
  estr = estr.replace(/\"/g, '\\\"');
  estr = estr.replace(/\'/g, '\\\'');
  return estr;
};
exports.HtmlDecode = function(estr){
  estr = estr.replace(/\\\'/g, '\'');
  estr = estr.replace(/\\\"/g, '"');
  estr = estr.replace(/&gt;/g, '>');
  estr = estr.replace(/&lt;/g, '<');
  estr = estr.replace(/&amp;/g, "&");
  return estr;
};
// 获取一个svg的根对象
exports.GetSvgRoot = function(eXmlString) {
  var doc = new DOMParser().parseFromString('<xml>' + eXmlString + '</xml>','text/xml');
  var xmlDocRoot = doc.documentElement;

  var xmlDocRootChildNodeList = xmlDocRoot.childNodes;
  var isvgrootnode;
  _.each(xmlDocRootChildNodeList, function(element, index, list){
    if(element.nodeName=='svg'){
      isvgrootnode=element;
    }
  });
  return isvgrootnode;
};

//随机数
exports.GetRandomInt = function(n) {
  return parseInt(Math.floor(Math.random()*n));
};

// 获取GUID
exports.GetGuid = function() {
  var guid = '';
  for (var i = 1; i <= 32; i++) {
    var n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
  }
  return guid;
};

// 遍历路径
exports.ScanFolderS = function(epath, eextname) {
  var fileList = [],
    walk = function(epath, fileList, folderList, ece){
      if(ece > 0){
        ece = ece - 1;
      }
      var files = fs.readdirSync(epath);
      files.forEach(function(item) {  
        var tmpPath = epath + item,
          stats = fs.statSync(tmpPath);
        if (!stats.isDirectory()) {
          if(eextname!=undefined){
            if(path.extname(tmpPath)==eextname){
              fileList.push(item); 
            }
          }else{
            fileList.push(item);
          }
        }
      });  
    };  

    walk(epath, fileList);

    //console.log('扫描' + epath +'成功');

    return fileList;
};
// 遍历路径
exports.ScanFolder = function(epath,eextname) {
  var fileList = [],
    folderList = [],
    walk = function(epath, fileList, folderList){
      var files = fs.readdirSync(epath);
      files.forEach(function(item) {  
        var tmpPath = epath + item,
            stats = fs.statSync(tmpPath);
        if (stats.isDirectory()) {  
            walk(tmpPath, fileList, folderList); 
            folderList.push(item); 
        } else {  
          if(eextname!=undefined){
            if(path.extname(tmpPath)==eextname){
              fileList.push(item); 
            }
          }else{
            fileList.push(item);
          }
        }  
      });  
    };  

    walk(epath, fileList, folderList);

    //console.log('扫描' + epath +'成功');

    return {
      'files': fileList,
      'folders': folderList
    }
};